package net.tolkv.tdd;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import com.scrumtrek.trainings.tdd.PaySystem;

public class BookStoreService extends ItemStoreService {
	private IStoreService storeService;

	private HashMap<String, List<Book>> authors;
	private HashMap<String, List<Book>> titles;

	private void init() {
		authors = new HashMap<String, List<Book>>();
		titles = new HashMap<String, List<Book>>();
	}

	public BookStoreService(IStoreService istore) {
		super(istore);
		init();
	}

	public BookStoreService(PaySystem paysystem, IStoreService istore) {
		super(paysystem, istore);
		init();
	}

	public Collection<Item> getItems() {
		return storeService.getItems();
	}

	public void sellItem(Item a) {
		getStoreService().sellItem(a);
	}

	public Item findItem(Item a) {
		return getStoreService().findItem(a);
	}

	public Item findItem(UUID id) {
		return getStoreService().findItem(id);
	}

	public int getTotalBooksAmount() {
		return getStoreService().getTotalItemsAmount();
	}

	public void addBook(Book book) {
		if (book == null)
			throw new NullPointerException("Add book is null");
		List<Book> tmp;
		if (!authors.containsKey(book.getAuthor())) {
			tmp = new ArrayList<Book>(1);
			tmp.add(book);
			authors.put(book.getAuthor(), tmp);
		} else {
			authors.get(book.getAuthor()).add(book);
		}

		if (!titles.containsKey(book.getTitle())) {
			tmp = new ArrayList<Book>(2);
			tmp.add(book);
			titles.put(book.getTitle(), tmp);
		} else {
			titles.get(book.getTitle()).add(book);
		}

		getStoreService().addItem(book);
	}

	public Set<String> getAuthors() {
		return authors.keySet();
	}

	public Set<String> getTitles() {
		System.out.println("KeySet: " + titles.keySet());
		return titles.keySet();
	}

	public List<Book> findByAuthor(String string) {
		return authors.get(string);
	}

	public List<Book> findByTitle(String string) {
		return titles.get(string);
	}

	public int getTotalItemsAmount() {
		return getStoreService().getTotalItemsAmount();
	}

	public int getProfit() {
		return getStoreService().getProfit();
	}

	public void addItem(Item book) {
		if (book == null)
			throw new NullPointerException("Add book is null");
		if (book instanceof Book) {
			addBook((Book) book);
		} else {
			super.addItem(book);
		}
	}

}
